package org.dprojects.iwebshare.ui.window;

import org.dprojects.iwebshare.main.iWebShareApplication;

import com.vaadin.event.Action;
import com.vaadin.event.ShortcutAction;
import com.vaadin.terminal.ExternalResource;
import com.vaadin.terminal.Sizeable;
import com.vaadin.ui.AbsoluteLayout;
import com.vaadin.ui.Button;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Window;

public class LoginWindow extends Window
{
    /**
	 * 
	 */
	private static final long serialVersionUID = -3634080880201899579L;
	
	private AbsoluteLayout layout = new AbsoluteLayout();
	private Panel loginPanel=new Panel("Login Panel");
	private Button btnLogin = new Button("Login");
    private TextField login = new TextField ( "Username");
    private PasswordField password = new PasswordField( "Password");


    public LoginWindow ()
    {
        super("Authentication Required !");
        setName ( "login" );
        initUI();
    }

    private void initUI ()
    {
    	
    	//layout.setWidth("100%"); 
    	//layout.setHeight("100%");
    	
    	loginPanel.setWidth(300, Sizeable.UNITS_PIXELS);
    	
    	
    	
        loginPanel.addComponent ( new Label ("Please login in order to use the application") );
    	loginPanel.addComponent ( new Label () );
    	loginPanel.addComponent ( login );
    	loginPanel.addComponent ( password );
    	loginPanel.addComponent ( btnLogin );
        
    	//this.setSizeFull();
    	
    	layout.addComponent(loginPanel, "left: 39%; top: 30%");
    	
    	setContent(layout);
    	
        btnLogin.addListener ( new Button.ClickListener()
        {
            /**
			 * 
			 */
			private static final long serialVersionUID = -5761028964917164760L;

			public void buttonClick ( Button.ClickEvent event )
            {
                try
                {
                    iWebShareApplication.getInstance ().authenticate((String)login.getValue (), (String)password.getValue ());
                    open( new ExternalResource(iWebShareApplication.getInstance ().getURL ()));
                }
                catch ( Exception e )
                {
                    showNotification ( e.toString ());
                }
            }
        });
        
        
		addActionHandler(new Action.Handler() {

			/**
			 * 
			 */
			private static final long serialVersionUID = 6868140226518824806L;
			
			final Action enter = new ShortcutAction("enter",
					ShortcutAction.KeyCode.ENTER, null);

			public Action[] getActions(Object target, Object sender) {
				return new Action[] { enter };
			}

			public void handleAction(Action action, Object sender, Object target) {
				if (action == enter) {
					System.out.println(action);
				}
			}

		});

    }
}